package com.lz.sports.vm

import android.widget.Toast
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import com.lz.comm.SP
import com.lz.helper.idcard.IDCardInfo
import com.lz.library.base.BaseModel
import com.lz.library.base.BaseViewModel
import com.lz.library.base.SingleLiveData
import com.lz.library.extension.showToast
import com.lz.library.utils.FileUtils
import com.lz.sports.R
import com.lz.sports.bean.DeviceGroup
import com.lz.sports.bean.ExamInspect
import com.lz.sports.bean.ExamInspectGroup
import com.lz.sports.bean.Examinee
import com.lz.sports.core.*
import com.lz.sports.db.DeviceDatabase
import com.lz.sports.db.ExamineeDatabase
import com.lz.sports.ui.checkmodel.ExamineeAndCardInfo
import com.lz.sports.ui.checkmodel.FeatureResult
import com.lz.sports.utils.ToastUtils
import com.lz.sports.utils.UploadUtils
import com.lz.sports.utils.toArrayList
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.withContext


//检录
class InspectViewModel : BaseViewModel<BaseModel>() {

    val examPlanId = ProjectManager.examPlanId()

    //项目ID
    val projectId = ProjectManager.examProjectId()

    //项目名称
    val projectName = ProjectManager.examProjectName()

    //考区ID
    val examAreaId = ProjectManager.examAreaId()

    //考点ID
    val examSiteId = ProjectManager.examSiteId()

    //检录方式
    val inspectType = VerifyManager.inspectModel().type

    //当前模式
    val currentModel = MutableLiveData<String>()
    val models by lazy { R.array.inspectModels.toArrayList() }
    var modelPosition = -1

    //当前组
    val currentGroup = MutableLiveData<DeviceGroup>()
    var groupList: List<DeviceGroup>? = null
    var groupPosition = -1

    //当前检录考生
    val currentExamInspect = MutableLiveData<ExamInspect>()

    //人脸识别去匹配监听
    val examineeAndCardInfo = MutableLiveData<ExamineeAndCardInfo>()

    //最大考次数
    private val maxCount = SP.getInt(K_RULE_EXAM_COUNT, v_ruleExamCount)

    //是否允许补考
    private val examResit = SP.getBoolean(K_RULE_EXAM_RESIT, v_ruleExamResit)

    //保存完成
    val saveOver = SingleLiveData(false)

    //检录组, 检录数量, 未检录
    val inspectGroupCount = MutableLiveData(0L)
    val inspectCount = MutableLiveData(0L)
    val unInspectCount = MutableLiveData(0L)

    override fun onCreate(owner: LifecycleOwner) {
        launch {
            val job = async(Dispatchers.IO) {
                inspectGroupCount.postValue(
                    ExamineeDatabase.get().inspectGroupCount(examPlanId, projectId, examAreaId, examSiteId)
                )
                inspectCount.postValue(
                    ExamineeDatabase.get().inspectCount(examPlanId, projectId, examAreaId, examSiteId)
                )
                unInspectCount.postValue(
                    ExamineeDatabase.get().examineeUnInspectCount(examPlanId, projectId, examAreaId, examSiteId)
                )
                DeviceDatabase.get().findDeviceGroupList(projectId)
            }
            groupList = job.await()
            if (groupList!!.isNotEmpty()) selectGroup(0)
            selectModel(0)
        }
    }

    //选择组
    fun selectGroup(position: Int) {
        if (groupPosition == position) return
        groupPosition = position
        currentGroup.value = groupList!![position]
    }

    //选择模式
    fun selectModel(position: Int): Boolean {
        if (position == modelPosition) return false
        modelPosition = position
        currentModel.value = models[position]
        return true
    }

    fun save(list: List<ExamInspect>) {
        val group = currentGroup.value
        if (group == null) {
            R.string.group_un.showToast()
            return
        }
        launch {
            updateDialogLoading(true)
            withContext(Dispatchers.IO) {
                val inspectGroup =
                    ExamInspectGroup(group.id, examPlanId, projectId, projectName, examAreaId, examSiteId)
                ExamineeDatabase.get().insertExamInspectList(list, inspectGroup)
                FileUtils.deleteFiles(UploadUtils.examInspectTmpPath()) //保存时清空临时文件夹
                ExamineeDatabase.get()
                    .updateExamInspectStatus(examPlanId, projectId, examAreaId, examSiteId, list.map { it.examineeId })
                inspectGroupCount.postValue(
                    ExamineeDatabase.get().inspectGroupCount(examPlanId, projectId, examAreaId, examSiteId)
                )
                inspectCount.postValue(
                    ExamineeDatabase.get().inspectCount(examPlanId, projectId, examAreaId, examSiteId)
                )
                unInspectCount.postValue(
                    ExamineeDatabase.get().examineeUnInspectCount(examPlanId, projectId, examAreaId, examSiteId)
                )
            }
            updateDialogLoading(false)
            ToastUtils.showMyToast(R.string.saveSuccess)
            saveOver.setValue(true)
        }
    }

    //添加人脸识别后的考生
    fun addExamInspect(featureResult: FeatureResult) {
        launch {
            withContext(Dispatchers.Default) {
                currentExamInspect.postValue(ExamInspect(featureResult))
            }
        }
    }
/*

    //查询考生信息
    fun findExamineeByIDCardInfo(idCardInfo: IDCardInfo): Examinee? {
        val examinee = ExamineeDatabase.get().findExamineeByIdCard(examPlanId, examAreaId, examSiteId, idCardInfo.num)
        examineeStatus(examinee).takeIf { it != 0 }?.also {
            launch {
                ToastUtils.showMyToast(it, Toast.LENGTH_SHORT)
            }
        }
        return examinee
    }
*/

    //身份证查找考生
    fun examineeIdCard(idCardInfo: IDCardInfo) {
        launch {
            val asyncJob = async(Dispatchers.Default) {
                val examinee =
                    ExamineeDatabase.get().findExamineeByIdCard(examPlanId, examAreaId, examSiteId, idCardInfo.num)
                examineeStatus(examinee).also { status ->
                    if (status == 0) {
                        currentExamInspect.postValue(ExamInspect(examinee!!, idCardInfo))
                    }
                }
            }
            asyncJob.await().takeIf { it != 0 }?.also { ToastUtils.showMyToast(it, Toast.LENGTH_SHORT) }
        }
    }

    //人脸识别信息
    fun examineeFace(idCardInfo: IDCardInfo) {
        launch {
            val asyncJob = async(Dispatchers.Default) {
                val examinee =
                    ExamineeDatabase.get().findExamineeByIdCard(examPlanId, examAreaId, examSiteId, idCardInfo.num)
                val status = examineeStatus(examinee).also {
                    if (it == 0) {//考生信息查找成功且可以检录
                        examineeAndCardInfo.postValue(ExamineeAndCardInfo(examinee!!, idCardInfo))
                    }
                }
                status
            }
            asyncJob.await().takeIf { it != 0 }?.also { ToastUtils.showMyToast(it, Toast.LENGTH_SHORT) }
        }
    }

    private fun examineeStatus(examinee: Examinee?): Int {
        if (examinee == null) return R.string.inspect_in_none //未找到该学生
        val examResult =
            ExamineeDatabase.get().findExamResult(examinee.id, examPlanId, projectId, examAreaId, examSiteId)
                ?: return R.string.inspect_project_none
        //考生没有报考该项目
        if (!examResit && examResult.isLack()) return R.string.inspect_lack
        if (ExamineeDatabase.get()
                .inspectCount(examinee.id, examPlanId, projectId, examAreaId, examSiteId) >= maxCount
        ) return R.string.inspect_exceed
        return 0
    }
}